<?php

namespace App\Repositories\Alipay;

use GuzzleHttp\Client;

class AlipayUserRepository
{


    private $config = [];
    private $client;

    public function __construct(
        Client $client
    )
    {
        $this->client = $client;
    }


    public function _config($config)
    {
        $this->config = $config;

        // 通过 bindRef 赋值对应的配置
        $this->config['app_id'] = config('union.alipay.app_id');
        $this->config['app_secret'] = config('union.alipay.app_secret');
    }

    /**
     * @param string $scopes
     * @param string $callback
     *
     * @return string
     */
    public function authorizeUrl($scopes = 'snsapi_base', $callback = '')
    {

        $url = '?';
        $params = [
            'appid'            => $this->config['app_id'],
            'scope'            => $scopes,
            'redirect_uri'     => $callback,
            'response_type'    => 'code',
            'state'            => $this->config['bindRef'],
            'connect_redirect' => 1,
        ];

        return $url . http_build_query($params) ;
    }



    public function authorizeToken($code, $extend)
    {
        $url = 'access_token';
        $params = [
            'appid'      => $this->config['app_id'],
            'secret'     => $this->config['app_secret'],
            'code'       => $code,
            'grant_type' => 'authorization_code',
        ];

        try {
            $rs = $this->client->request('GET', $url, [
                'query' => $params
            ]);

            // 异常处理
            if (empty($rs) ||
                $rs->getStatusCode() != 200
            ) {

                return [];
            }

            $getContents = $rs->getBody()->getContents();
            $result = !empty($getContents) ? json_decode($getContents, true) : [];

            return $result;

        } catch (\Exception $exception) {

            return [];
        }
    }


    public function authorizeUser($openID, $accessToken)
    {
        $url = 'userinfo';
        $params = [
            'access_token' => $accessToken,
            'openid'       => $openID,
            'lang'         => 'zh_CN',
        ];
        try {
            $rs = $this->client->request('GET', $url, [
                'query' => $params
            ]);

            // 异常处理
            if (empty($rs) ||
                $rs->getStatusCode() != 200
            ) {
                return [];
            }

            $getContents = $rs->getBody()->getContents();
            $result = !empty($getContents) ? json_decode($getContents, true) : [];

            return $result;

        } catch (\Exception $exception) {

            return [];
        }
    }


}